package com.zhouxin.customview.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.zhouxin.customview.extensions.dp2px
import kotlin.math.cos
import kotlin.math.sin

/**
 * Copyright©
 * FileName: PieView
 * Author: ZhouXin
 * Date: 2022/6/3
 * Description:饼图
 * Tips:
 *  (index, element) in Arrays.withIndex()的使用
 */
private val RADIUS = 150f.dp2px
private val ANGLES = floatArrayOf(60f, 100f, 120f, 80f)
private val COLORS = listOf(
    Color.parseColor("#C2185B"),
    Color.parseColor("#00ACC1"),
    Color.parseColor("#55882F"),
    Color.parseColor("#fD4037")
)
private val OFFSET_LENGTH = 20f.dp2px

class PieView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    override fun onDraw(canvas: Canvas) {
        var startAngle = 0f;
        for ((index, angle) in ANGLES.withIndex()) {
            paint.color = COLORS[index]
            if (index == 1) {
                canvas.save()
                canvas.translate(
                    (OFFSET_LENGTH * cos(Math.toRadians((startAngle + angle / 2f).toDouble()))).toFloat(),
                    (OFFSET_LENGTH * sin(Math.toRadians((startAngle + angle / 2f).toDouble()))).toFloat()
                )
            }
            canvas.drawArc(
                width / 2f - RADIUS,
                height / 2f - RADIUS,
                width / 2f + RADIUS,
                height / 2f + RADIUS,
                startAngle,
                angle,
                true,
                paint
            )
            startAngle += angle
            if (index == 1) {
                canvas.restore()
            }
        }

    }
}